package com;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class KeyGenerator {

    public static void main(String[] args) throws Exception {
        // 生成 RSA 密钥对（2048位）
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair keyPair = keyGen.generateKeyPair();

        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // 编码为 Base64 便于存储
        String priKey = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        String pubKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());

        System.out.println("🔐 私钥（Base64）：" + priKey);
        System.out.println("🔐 公钥（Base64）：" + pubKey);

        // 写入文件
        Files.write(Paths.get("D:/private.key"), priKey.getBytes());
        Files.write(Paths.get("D:/public.key"), pubKey.getBytes());

        System.out.println("✅ 私钥已保存：D:\\private.key");
        System.out.println("✅ 公钥已保存：D:\\public.key");
    }
}